import { ListVO, saveRole } from '../services';
import { Dialog, Field, Form, Input, Select, Switch } from '@alifd/next';
import { useEffect } from 'react';
import { useRequest } from 'ice';
import { EnableStatus } from '@/common/entity';

interface Props {
  visible?: boolean;
  onClose?: () => any;
  onRefresh?: () => any;
  record?: ListVO;
}

const { Item: FormItem } = Form;

const formItemLayout = {
  labelCol: {
    fixedSpan: 8,
  },
  wrapperCol: {
    span: 10,
  },
};

function EditDialog({ visible, onClose, record, onRefresh }: Props) {
  const form = Field.useField([{}]);
  const { loading, request } = useRequest<string, ListVO[]>(saveRole, {
    defaultParams: [{}],
    debounceInterval: 300,
    onSuccess: () => {
      onClose?.();
      onRefresh?.();
    },
  });

  useEffect(() => {
    if (visible) {
      let fromValues = {
        status: true,
      };
      if (record) {
        fromValues = {
          ...record,
          status: record?.status == EnableStatus.ENABLE,
        };
      }
      form.setValues(fromValues);
    }
  }, [visible]);

  const onSubmit = () => {
    form.validateCallback((errors: any[], values: any) => {
      if (errors) {
        return;
      }
      request({ ...values, status: values.status ? 1 : 0, id: record?.id });
    });
  };

  return (
    <Dialog
      title={record?.id ? '编辑角色' : '新增角色'}
      v2
      visible={visible}
      overflowScroll
      width="50%"
      onOk={onSubmit}
      onClose={onClose}
      afterClose={() => form.reset()}
      okProps={{ loading }}
      cancelProps={{ loading }}
    >
      <Form {...formItemLayout} disabled={loading} field={form} fullWidth colon useLabelForErrorMessage>
        <FormItem name="id" label="id" style={{ display: 'none' }}>
          <Input />
        </FormItem>
        <FormItem name="name" label="角色名称" required>
          <Input />
        </FormItem>
        <Form.Item label="角色类型" required>
          <Select
            name="type"
            placeholder="请选择"
            hasClear
            dataSource={[
              { value: 1, label: '系统角色' },
              { value: 2, label: '业务角色' },
            ]}
          />
        </Form.Item>
        <FormItem name="code" label="角色编码" required>
          <Input />
        </FormItem>
        <FormItem name="status" label="状态">
          <Switch autoWidth size="small" checkedChildren="启用" unCheckedChildren="禁用" />
        </FormItem>
      </Form>
    </Dialog>
  );
}

export default EditDialog;
